from django.shortcuts import render
from users.models import *
from rest_framework.views import APIView
from rest_framework.response import Response
from .ser import *
# Create your views here.
#读取首页三级分类
class Home(APIView):
    def get(self,request):
        #读取一级
        cates = Category.objects.filter(parent_id__isnull=True).all()
        list=[]
        for i in cates:
            dict={}
            dict['id'] = i.id
            dict['name'] = i.name
            #读取二级
            two = i.subs.all()
            print(two)
            twolist=[]
            #遍历二级获取三级
            for j in two:
                twodict={}
                twodict['id'] = j.id
                twodict['name'] = j.name
                three = j.subs.all()
                ser = CateSer(three,many=True)
                twodict['subs'] = ser.data
                twolist.append(twodict)

            dict['subs'] = twolist
            list.append(dict)

        #查询一级分类，一级下面的二级，一级下面的三级，一级下面所有的东西
        categoods = []
        for j in cates:
            dict = {}
            dict['id']=j.id
            dict['name']=j.name
            dict['pic']=str(j.pic)
            two = j.subs.all()
            twoser = CateSer(two,many=True)
            dict['two'] = twoser.data
            #获取三级
            print(j.id)
            three = Category.objects.filter(top_parent=j.id,level=3).all()
            threeser = CateSer(three,many=True)
            dict['three'] = threeser.data
            #获取商品，排序，新品按时间倒序排，价格，销量
            sorted = request.GET.get('sorted')
            topid = request.GET.get('topid')

            goods = Goods.objects.filter(category1_id=j.id,home_show=1).all()
            if sorted:
                if int(topid)==int(j.id):
                    goods = Goods.objects.filter(category1_id=j.id,home_show=1).order_by('-'+sorted).all()

            gser = GoodsSer(goods,many=True)
            dict['goods'] = gser.data
            categoods.append(dict)

        return Response({"code":200,'catelist':list,'categoods':categoods})

class GoodM(APIView):
    def get(self,request):
        id = request.GET.get('id')
        good = Goods.objects.filter(id=id).first()
        ser = GoodsSer(good)
        return Response({'code':200,'good':ser.data})

class CartM(APIView):
    def post(self,request):
        #判断用户是否购买过此商品
        userid = request.data.get('user')
        goodsid = request.data.get('goods')
        number = int(request.data.get('number'))
        cart = Cart.objects.filter(user_id=userid,goods=goodsid).first()
        if cart:
            #如果买过数量+
            cart.number+=number
            cart.save()
            return Response({'code':200})
        else:
            #没买过购物车新增一条记录
            ser = CartSer(data=request.data)
            if ser.is_valid():
                ser.save()
            else:
                print(ser.errors)
                return Response({'code':10010})
            return Response({'code':140})

    def get(self,request):
        userid = request.GET.get('userid')
        cate = Cart.objects.filter(user_id=userid).all()
        ser = ShowCartSer(cate,many=True)
        #全选
        selected_all = True
        total = 0
        select_total = 0
        select_money = 0
        for i in cate:
            total += i.number
            if i.is_checked == False:
                selected_all = False
            else:
                select_total += i.number
                goods = Goods.objects.filter(id=i.goods_id).first()
                select_money += i.number * float(goods.price)
        return Response({'code':200,'list':ser.data,'selected_all':selected_all,'total':total,
                         'select_total':select_total,'select_money':select_money})

    def delete(self,request):
        id = request.GET.get('id')
        cate = Cart.objects.filter(id=id).delete()
        ser = CartSer(cate,many=True)
        return Response({'code':200})

    def put(self, request):
        id = request.GET.get('id')
        cart = Cart.objects.filter(id=id).first()
        if cart.is_checked == True:
            cart.is_checked = False
        else:
            cart.is_checked = True
        cart.save()
        return Response({"code": 200})

#全选
class SelectAll(APIView):
    def put(self,request):
        userid = request.GET.get('userid')
        selected_all = request.GET.get('selected_all')
        if selected_all == 'true':
            Cart.objects.filter(user_id=userid).update(is_checked=True)
        else:
            Cart.objects.filter(user_id=userid).update(is_checked=False)
        return Response({'code':200})

    def post(self,request):
        id = request.data.get('id')
        type = request.data.get('type')
        count = request.data.get('count')
        cart = Cart.objects.filter(id=id).first()
        if type ==1:
            #加
             cart.number +=1
        elif type == 2:
            #减
            #判断是否>1
            if cart.number>1:
                cart.number -=1
        else:
            #数量更新
            cart.number = int(count)
        cart.save()
        return Response({"code":200})

class Getcart(APIView):
    def get(self,request):
        userid = request.GET.get('userid')
        cart = Cart.objects.filter(user_id=userid,is_checked=True).all()
        ser = ShowCartSer(cart,many=True)
        total=0
        tmoney=0
        pic=''
        for i in ser.data:
            total += i['number']
            tmoney += float(i['goods']['price'])*i['number']

        return Response({'code':200,'total':total,'tmoney':tmoney,})


import datetime
import random
from django.db import transaction
from users.ser import *

# 生成订单接口
class CreateOrders(APIView):
    @transaction.atomic
    def post(self, request):
        # 获取userid
        userid = request.data.get('userid')
        address_id = request.data.get('address_id')
        pay_method = request.data.get('pay_method')
        print(userid,address_id,pay_method)
        # 根据userid查询购物车中已经选中的记录
        cart = Cart.objects.filter(user_id=userid, is_checked=True).all()
        cartser = ShowCartSer(cart, many=True)
        # 遍历购物车
        total_amount = 0
        for i in cartser.data:
            total_amount += i['number'] * float(i['goods']['price'])
        # 生成订单号
        order_no = datetime.datetime.strftime(datetime.datetime.now(), '%Y%M%D%H%M%S') + str(userid) + str(
            random.randint(1000, 9999))
        # 查找地址构造地址信息
        add = Address.objects.filter(id=address_id).first()
        addressSer = ShowAddressser(add)
        address = addressSer.data
        addressStr = str(address['province']) + ' ' + str(address['city']) + ' ' + str(address['area']) + ' ' + str(address[
            'address']) + ' ' + str(address['receive']) + ' ' + str(address['mobile'])

        datam = {'order_no': order_no, 'user': userid, 'address': addressStr, 'total_amount': total_amount,
                 'pay_method': pay_method}
        # 创建事务结点
        sid = transaction.savepoint()
        try:
            # 调用序列化器添加订单
            ser = OrderInfoSer(data=datam)
            if ser.is_valid():
                ser.save()
                # 生成订单详情
                for i in cartser.data:
                    detaildata = {'order': order_no, 'goods': i['goods']['id'],
                                  'goodsname': i['goods']['name'], 'images': i['goods']['pic'],
                                  'count': i['number'], 'price': float(i['goods']['price']), 'user': userid}
                    # 调用序列化器添加订单详情
                    dser = OrderDetailSer(data=detaildata)
                    if dser.is_valid():
                        dser.save()
            # 购物车删除已经生成订单的记录
            Cart.objects.filter(user_id=userid, is_checked=True).delete()
            # 提交事务
            transaction.savepoint_commit(sid)
            # 返回结果
            return Response({'code': 200, 'order_no': order_no, 'tmoney': total_amount})
        except:
            # 事务回滚
            transaction.savepoint_rollback(sid)
            return Response({'code': 20010})

# 🤘🏻
# 🤘🏻




